package com.sanshow.charging;

import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.sanshow.charging.data.DownCommand;
import com.sanshow.charging.data.LoginBean;
import com.sanshow.charging.data.NowVersionBean;
import com.sanshow.charging.data.PulseBean;
import com.sanshow.charging.data.TaskCommand;
import com.sanshow.charging.data.UploadBean;
import com.sanshow.charging.db.Charging;
import com.sanshow.charging.db.ChargingDao;
import com.sanshow.charging.db.ChargingDelay;
import com.sanshow.charging.db.ChargingDelayDao;
import com.sanshow.charging.db.ChargingMirror;
import com.sanshow.charging.db.ChargingMirrorDao;
import com.sanshow.charging.fragment.BaseFragment;
import com.sanshow.charging.fragment.ImageFragment;
import com.sanshow.charging.fragment.LoginDailogFragment;
import com.sanshow.charging.fragment.VideoFragment;
import com.sanshow.charging.gson.DeviceInfo;
import com.sanshow.charging.updater.Updater;
import com.sanshow.charging.updater.UpdaterConfig;
import com.sanshow.charging.util.AnimationUtil;
import com.sanshow.charging.util.ConstUtil;
import com.sanshow.charging.util.DeviceUtil;
import com.sanshow.charging.util.DialogUtil;
import com.sanshow.charging.util.DialogWithChooseUtil;
import com.sanshow.charging.util.FileUtils;
import com.sanshow.charging.util.HttpUtil;
import com.sanshow.charging.util.ImageDownload;
import com.sanshow.charging.util.UpdateInfo;
import com.sanshow.charging.util.UpdateUtils;
import com.sanshow.charging.util.UploadDataUtil;
import com.sanshow.charging.util.Utility;
import com.sanshow.charging.util.VideoDownload;
import com.xuhao.didi.core.iocore.interfaces.ISendable;
import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import ZtlApi.ZtlManager;
import me.f1reking.serialportlib.SerialPortHelper;
import me.f1reking.serialportlib.entity.DATAB;
import me.f1reking.serialportlib.entity.FLOWCON;
import me.f1reking.serialportlib.entity.PARITY;
import me.f1reking.serialportlib.entity.STOPB;
import me.f1reking.serialportlib.listener.IOpenSerialPortListener;
import me.f1reking.serialportlib.listener.ISerialPortDataListener;
import me.f1reking.serialportlib.listener.Status;
import me.f1reking.serialportlib.util.ByteUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    LinearLayout frameLayout;
    LinearLayout mLlIndex1;
    LinearLayout mLlIndex2;
    LinearLayout mLlIndex3;
    Button mBtnBorrow;
    Button mBtnBack;
    Button mBtnReturn;
    Button mBtnReturnBack; // 归还，返回按钮
    Button mBtnBackBattery;
    Button mBtnBackWakeboard;
    TextClock mTvNow;
    TextView mTvFees;
    ImageView mLogo;
    ImageView mIvWeixin;
    ImageView mIvNetState;
    TextView mTvName;
    TextView mTvCode;
    TextView mTvFooter;
    TextView mTvBackShow;

    private final String TAB_FRAGMENT_MAIN = "TAB_FRAGMENT_MAIN";
    private ImageFragment imageFragment;
    private VideoFragment videoFragment;
    private BaseFragment baseFragment;


    private ConnectionInfo mInfo;
    private IConnectionManager mManager;

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    private static String logFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/sanshow/logs/";
    private static String logFileName = TimeUtils.date2String(new Date(), "yyyy-MM-dd") + ".txt";

    private SerialPortHelper mSerialPortHelper;
    public BlockingQueue<byte[]> dataQueue = new LinkedBlockingQueue<>();
    private ProgressDataThread mProgressDataThread;
    private SendThread mSendThread;

    // 开门任务队列
    public static BlockingQueue<TaskCommand> taskQueue = new LinkedBlockingQueue<>();
    // 响应门开了，返回任务队列
    public static List<String> openDoorTaskQueue = new ArrayList<>();
    // 响应借关门，返回任务队列
    public static BlockingQueue<String> borrowCloseDoorTaskQueue = new LinkedBlockingQueue<>();
    // 响应还关门，返回任务队列
    public static BlockingQueue<String> backCloseDoorTaskQueue = new LinkedBlockingQueue<>();
    // 实时响应关门上报，用于心跳上，发送关门当前的状态
    public static Map<String, String> responseCloseDoorTaskList = new HashMap<String, String>();
    // 存放小程序下发开门命令的浮板、电池编号列表
    //public static List<String> wbList = new ArrayList<>();

    private boolean isFinished = false;
    private String nowCmdItemCode = "";

    private String nowBackingBattery = "";
    private String nowBackingWakeboard = "";

    // 用于借 计时
    private static int BORROW_TOTAL_TIME_20 = 20;
    private Timer timerBorrow;

    // 用于还 计时
    private static int BACK_TOTAL_TIME_30 = 30;
    private Timer timerBack;

    // 用于还电池【门窗弹开】 计时
    private static int BACK_ALERT_BATTERY_TOTAL_TIME_30 = 30;
    private Timer timerBackAlertBattery;

    // 用于还浮板【先还电池提示】 计时
    private static int BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 = 12;
    private Timer timerBackAlertWakeBoardTip;

    // 用于还浮板【门窗弹开】 计时
    private static int BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;
    private Timer timerBackAlertWakeBoard;

    // 连续点击显示 【还浮板】
    private long timeLong = 1000; // 两次点击时长
    private long clickCount = 0; // 当前点击次数
    private long lastTimeClick = 0; // 上次计时
    private long newTimeClick = 0; // 最新计时

    // socket初始化完成
    private boolean isSocketInited = false;
    // 第一次网络状态
    private boolean isFirstNetState = true;

    // 借还按钮 避免重复点击
    private long mBorrowLastClickTime = 0L;
    private long mBackLastClickTime = 0L;
    private long timeInterval = 1000L;

    // 还电池、还浮板 避免重复点击
    private long mBackBatteryClickTime = 0L;
    private long mBackWakeBoardClickTime = 0L;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏

        initView();
        //SPUtils.getInstance().put("currentTemplate", "video");
        initFragment();
        requestPermission();
        recoverData();

        // 声明并实例化 ZtlManager 对象
        ZtlManager.GetInstance().setContext(MainActivity.this);

        // ZtlManager.GetInstance().setTouchOrientation(90,false);
        // ZtlManager.GetInstance().setDisplayOrientation(90);

        // 网络监听
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, intentFilter);



        /*String log = TimeUtils.date2String(new Date(),"yyyy-MM-dd HH:mm:ss.SSS") +"  - testtesttest";
        FileUtils.writeTxtToFile(log, logFilePath, logFileName);*/
        // 保留一个月日志
        handleOpenLog();

    }

    private final BroadcastReceiver connectionReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (!NetworkUtils.isConnected()) {
                Log.i(TAG, "网络连接失败---网络已经断开");
                Toast.makeText(MainActivity.this, "网络已经断开！", Toast.LENGTH_LONG).show();
                mIvNetState.setImageResource(R.mipmap.no_wifi);
                mIvWeixin.setImageResource(R.mipmap.net_error);
                mManager.disconnect();

            } else {
                Log.i(TAG, "网络连接成功");
                if (!isFirstNetState) {
                    AppUtils.relaunchApp(true);
                }
            }

            isFirstNetState = false;
        }
    };

    @Override
    protected void onResume() {
        Log.e(TAG, "=============================返回===========================");
        super.onResume();
        if (!isSocketInited) {
            initSocket();
        } else {
            requestUpdateItems();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        close();
        relese();

        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }
    }

    // 异常退出、奔溃，数据恢复处理
    private void recoverData() {
        long nowSaveDataTimeStamp = SPUtils.getInstance().getLong("nowSaveDataTimeStamp", 0L);
        String nowStateData = SPUtils.getInstance().getString("responseCloseDoorTaskList", "");
        //String nowWbList = SPUtils.getInstance().getString("wbList", "");
        if (nowSaveDataTimeStamp != 0L) {
            long oldDataTime = nowSaveDataTimeStamp;
            long newLong = TimeUtils.getNowMills() / 1000;
            if (newLong - oldDataTime <= 600) {
                if (!StringUtils.isEmpty(nowStateData)) {
                    responseCloseDoorTaskList = GsonUtils.fromJson(nowStateData, responseCloseDoorTaskList.getClass());
                    if (responseCloseDoorTaskList.size() > 0) {
                        for (Map.Entry<String, String> entry : responseCloseDoorTaskList.entrySet()) {
                            String key = entry.getKey();
                            String value = entry.getValue();
                            if (value.equals("2")) {
                                backCloseDoorTaskQueue.add(key);
                            } else {
                                borrowCloseDoorTaskQueue.add(key);
                            }
                        }
                    }

                    SPUtils.getInstance().put("responseCloseDoorTaskList", "");
                }

                /*if (!StringUtils.isEmpty(nowWbList)) {
                    String[] wbSplit = nowWbList.split(",");
                    for (String item : wbSplit) {
                        wbList.add(item);
                    }

                    SPUtils.getInstance().put("wbList", "");
                }*/

                //SPUtils.getInstance().put("responseCloseDoorTaskList","");
                //SPUtils.getInstance().put("wbList","");
            }


        }
    }

    private void initView() {
        mTvNow = this.findViewById(R.id.tv_now);
        mTvFees = this.findViewById(R.id.tv_fees);

        mLlIndex1 = this.findViewById(R.id.ll_index1);
        mLlIndex2 = this.findViewById(R.id.ll_index2);
        mLlIndex3 = this.findViewById(R.id.ll_index3);
        mTvBackShow = this.findViewById(R.id.tv_back_show);
        mBtnBorrow = this.findViewById(R.id.btn_borrow);
        mBtnBack = this.findViewById(R.id.btn_back);
        mBtnReturn = this.findViewById(R.id.btn_return);
        mBtnReturnBack = this.findViewById(R.id.btn_return_back);
        mBtnBackBattery = this.findViewById(R.id.btn_back_battery);
        mBtnBackWakeboard = this.findViewById(R.id.btn_back_wakeboard);
        mTvName = this.findViewById(R.id.tv_name);
        mTvCode = this.findViewById(R.id.tv_code);
        mTvFooter = this.findViewById(R.id.tv_footer);

        mLogo = this.findViewById(R.id.iv_logo);
        mIvWeixin = this.findViewById(R.id.iv_weixin);
        mLogo.setOnClickListener(this);
        //mIvWeixin.setOnClickListener(this);
        mBtnBorrow.setOnClickListener(this);
        mBtnBack.setOnClickListener(this);
        mBtnReturn.setOnClickListener(this);
        mBtnReturnBack.setOnClickListener(this);
        mBtnBackBattery.setOnClickListener(this);
        mBtnBackWakeboard.setOnClickListener(this);
        //mTvBackShow.setOnClickListener(this);

        mIvNetState = this.findViewById(R.id.iv_net_state);
        mIvNetState.setImageResource(R.mipmap.no_wifi);

        /*View view = LayoutInflater.from(this).inflate(R.layout.index_image, frameLayout, false);

        ImageView imageView = (ImageView) view.findViewById(R.id.iv_banner);
        imageView.setImageResource(R.mipmap.banner);
        frameLayout.addView(view);*/

        //requestDeviceInfo();
        //requestAppUpgrade();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    private void initFragment() {
        String currentTemplate = SPUtils.getInstance().getString("currentTemplate");
        if (StringUtils.isEmpty(currentTemplate)) {
            SPUtils.getInstance().put("currentTemplate", "image");
            currentTemplate = "image";
        }
        if (currentTemplate.equals("image")) {
            imageFragment = ImageFragment.newInstance();
            baseFragment = imageFragment;
        } else if (currentTemplate.equals("video")) {
            videoFragment = VideoFragment.newInstance();
            baseFragment = videoFragment;
        }
        getSupportFragmentManager().beginTransaction()
                .add(R.id.frameLayout, baseFragment, TAB_FRAGMENT_MAIN)
                .commit();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_borrow: {
                long nowTime = System.currentTimeMillis();
                if (nowTime - mBorrowLastClickTime > timeInterval) {
                    mBorrowLastClickTime = nowTime;

                    mLlIndex1.setVisibility(View.GONE);
                    mLlIndex1.setAnimation(AnimationUtil.moveToViewBottom());
                    mLlIndex2.setVisibility(View.VISIBLE);
                    mLlIndex2.setAnimation(AnimationUtil.moveToViewLocation());
                    startBorrowTimer();
                }
                break;
            }
            case R.id.btn_back: {
                long nowTime = System.currentTimeMillis();
                if (nowTime - mBackLastClickTime > timeInterval) {
                    mBackLastClickTime = nowTime;

                    if (!NetworkUtils.isConnected()) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.buttonDialog);
                        builder.setIcon(R.mipmap.back_error)
                                .setTitle("提示")
                                .setMessage("当前网络故障，无法借还，请联系工作人员！")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .create().show();
                        //Toast.makeText(this, "当前网络故障，无法借还！", Toast.LENGTH_LONG).show();
                        return;
                    }

                    mLlIndex1.setVisibility(View.GONE);
                    mLlIndex1.setAnimation(AnimationUtil.moveToViewBottom());
                    mLlIndex3.setVisibility(View.VISIBLE);
                    mLlIndex3.setAnimation(AnimationUtil.moveToViewLocation());

                    /*if (wbList != null && wbList.size() > 0) {
                        long wakeBoardCount = wbList.stream().filter(str -> str.startsWith("9")).count();
                        long batteryCount = wbList.size() - wakeBoardCount;
                        if (wakeBoardCount != 0 && wakeBoardCount != batteryCount) {
                            mBtnBackBattery.setVisibility(View.GONE);
                            mBtnBackWakeboard.setVisibility(View.VISIBLE);
                            mBtnReturnBack.setVisibility(View.GONE);
                        } else {
                            mBtnBackBattery.setVisibility(View.VISIBLE);
                            mBtnBackWakeboard.setVisibility(View.GONE);
                            mBtnReturnBack.setVisibility(View.VISIBLE);
                            startBackTimer();
                        }
                    } else {
                        mBtnBackBattery.setVisibility(View.VISIBLE);
                        mBtnBackWakeboard.setVisibility(View.GONE);
                        mBtnReturnBack.setVisibility(View.VISIBLE);
                        startBackTimer();
                    }*/

                    startBackTimer();

                }
                break;
            }
            case R.id.btn_return: {
                mLlIndex2.setVisibility(View.GONE);
                mLlIndex2.setAnimation(AnimationUtil.moveToViewBottom());
                mLlIndex1.setVisibility(View.VISIBLE);
                mLlIndex1.setAnimation(AnimationUtil.moveToViewLocation());
                timerBorrow.cancel();
                BORROW_TOTAL_TIME_20 = 20;
                break;
            }
            // 返回，还按钮
            case R.id.btn_return_back: {
                mLlIndex3.setVisibility(View.GONE);
                mLlIndex3.setAnimation(AnimationUtil.moveToViewBottom());
                mLlIndex1.setVisibility(View.VISIBLE);
                mLlIndex1.setAnimation(AnimationUtil.moveToViewLocation());
                timerBack.cancel();
                BACK_TOTAL_TIME_30 = 30;
                break;
            }
            case R.id.iv_logo: {
                LoginDailogFragment fragment = new LoginDailogFragment();
                fragment.show(getSupportFragmentManager(), "login");
                break;
            }

            /*case R.id.btn_back_battery: {
                ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                List<Charging> chargingList = chargingDao.queryBuilder().where(ChargingDao.Properties.InfoCode.eq("00000000")).where(ChargingDao.Properties.ItemFlag.eq(1)).list();
                if (chargingList != null && chargingList.size() > 0) {
                    BACK_TOTAL_TIME_20 = 20;
                    timerBack.cancel();
                    mBtnReturnBack.setVisibility(View.GONE);

                    Charging charging = chargingList.get(0);
                    String itemCode = getItemCode(Integer.parseInt(charging.getItemCode()));
                    TaskCommand taskCommand = new TaskCommand(itemCode, "51", 1);
                    taskQueue.add(taskCommand);
                    openDoorTaskQueue.add(itemCode);
                    if (!responseCloseDoorTaskList.containsKey(itemCode)) {
                        responseCloseDoorTaskList.put(itemCode, "2");
                    }
                    backCloseDoorTaskQueue.add(itemCode);

                    nowBackingBattery = itemCode;
                    backBatteryDialog(charging.getItemCode());
                } else {
                    Toast.makeText(this, "没有可用电池仓门供打开", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.btn_back_wakeboard: {
                ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                List<Charging> chargingList = chargingDao.queryBuilder().where(ChargingDao.Properties.InfoCode.eq("00000000")).where(ChargingDao.Properties.ItemFlag.eq(2)).list();
                if (chargingList != null && chargingList.size() > 0) {
                    Charging charging = chargingList.get(0);
                    String itemCode = getItemCode(Integer.parseInt(charging.getItemCode()));
                    TaskCommand taskCommand = new TaskCommand(itemCode, "51", 1);
                    taskQueue.add(taskCommand);
                    openDoorTaskQueue.add(itemCode);
                    if (!responseCloseDoorTaskList.containsKey(itemCode)) {
                        responseCloseDoorTaskList.put(itemCode, "2");
                    }
                    backCloseDoorTaskQueue.add(itemCode);

                    nowBackingWakeboard = itemCode;
                    backWakeboardDialog(charging.getItemCode());
                } else {
                    Toast.makeText(MainActivity.this, "没有可用浮板仓门供打开", Toast.LENGTH_LONG).show();
                }
                break;
            }*/

            case R.id.btn_back_battery: {
                long nowTime = System.currentTimeMillis();
                if (nowTime - mBackBatteryClickTime > timeInterval) {
                    mBackBatteryClickTime = nowTime;
                    ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                    List<Charging> chargingListDoor = chargingDao.queryBuilder().where(ChargingDao.Properties.DoorStatus.eq("01")).list();
                    if (chargingListDoor != null && chargingListDoor.size() > 0) {
                        Toast.makeText(this, "当前还有仓门未关，请帮忙关门，再还电池！", Toast.LENGTH_LONG).show();
                        return;
                    }

                    String needItemCode = getEmptyItemCode(1);
                    if (!StringUtils.isEmpty(needItemCode)) {
                        BACK_TOTAL_TIME_30 = 30;
                        //timerBack.cancel();
                        //mBtnReturnBack.setVisibility(View.GONE);

                        String itemCode = getItemCode(Integer.parseInt(needItemCode));
                        TaskCommand taskCommand = new TaskCommand(itemCode, "51", 1);
                        taskQueue.add(taskCommand);
                        openDoorTaskQueue.add(itemCode);
                        if (!responseCloseDoorTaskList.containsKey(itemCode)) {
                            responseCloseDoorTaskList.put(itemCode, "2");
                            backCloseDoorTaskQueue.add(itemCode);
                        }

                        nowBackingBattery = itemCode;
                        backBatteryDialog(needItemCode);
                    } else {
                        Toast.makeText(this, "没有可用电池仓门供打开", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }
            case R.id.btn_back_wakeboard: {
                long nowTime = System.currentTimeMillis();
                if (nowTime - mBackWakeBoardClickTime > timeInterval) {
                    mBackWakeBoardClickTime = nowTime;
                    ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                    List<Charging> chargingListDoor = chargingDao.queryBuilder().where(ChargingDao.Properties.DoorStatus.eq("01")).list();
                    if (chargingListDoor != null && chargingListDoor.size() > 0) {
                        Toast.makeText(this, "当前还有仓门未关，请帮忙关门，再还浮板！", Toast.LENGTH_LONG).show();
                        return;
                    }

                    String needItemCode = getEmptyItemCode(2);
                    if (!StringUtils.isEmpty(needItemCode)) {
                        BACK_TOTAL_TIME_30 = 30;
                        backWakeboardTipDialog(needItemCode);
                    } else {
                        Toast.makeText(MainActivity.this, "没有可用浮板仓门供打开", Toast.LENGTH_LONG).show();
                    }
                }
                break;
            }

            /*case R.id.tv_back_show: {
                showBackWakeBoardButton();
                break;
            }*/

        }
    }

    // 还时获取空仓门 号
    private String getEmptyItemCode(int itemFlag) {
        ChargingMirrorDao chargingMirrorDao = MyApplication.getDaoInstant().getChargingMirrorDao();
        List<ChargingMirror> chargingMirrorList = chargingMirrorDao.queryBuilder().where(ChargingMirrorDao.Properties.InfoCode.eq("00000000")).where(ChargingMirrorDao.Properties.DoorStatus.eq("00")).where(ChargingMirrorDao.Properties.IsAvailable.eq(1)).where(ChargingMirrorDao.Properties.ItemFlag.eq(itemFlag)).list();
        if (chargingMirrorList != null && chargingMirrorList.size() > 0) {
            return chargingMirrorList.get(0).getItemCode();
        } else {
            return "";
        }
    }

    AlertDialog alertDialogBatteryTip = null;

    private void backBatteryDialog(String itemCode) {
        DialogUtil.showAlertDialog(MainActivity.this, R.mipmap.back_device, "归还电池提示", "电池仓门【" + itemCode + "】已经打开，请归还电池并关好仓门！",
                "确定", "", false, new DialogUtil.AlertDialogBtnClickListener() {
                    @Override
                    public void clickPositive(AlertDialog dialog) {
                        //Toast.makeText(MainActivity.this, "点击了确定的按钮", Toast.LENGTH_SHORT).show();
                        if (StringUtils.isEmpty(nowBackingBattery)) {
                            timerBackAlertBattery.cancel();
                            BACK_ALERT_BATTERY_TOTAL_TIME_30 = 30;

                            Toast.makeText(MainActivity.this, "当前电池已归还", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                            //mBtnBackBattery.setVisibility(View.GONE);
                            //mBtnBackWakeboard.setVisibility(View.VISIBLE);
                            startBackTimer();
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.buttonDialog);
                            alertDialogBatteryTip = builder.setIcon(R.mipmap.back_error)
                                    .setTitle("提示")
                                    .setMessage("请先归还电池")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                        }
                                    })
                                    .create();
                            alertDialogBatteryTip.show();
                            BACK_ALERT_BATTERY_TOTAL_TIME_30 = 30;
                        }
                    }

                    @Override
                    public void clickNegative() {
                        Toast.makeText(MainActivity.this, "已取消", Toast.LENGTH_SHORT).show();
                        if(timerBackAlertWakeBoard != null){
                            timerBackAlertWakeBoard.cancel();
                            BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;
                        }
                    }
                });

        if (DialogUtil.positiveButton != null) {
            startBackAlertBatteryTimer();
        }
    }

    // 弹出浮板 -- 提醒
    private void backWakeboardTipDialog(String needItemCode) {
        DialogWithChooseUtil.showAlertDialog(MainActivity.this, R.mipmap.back_device, "浮板归还提醒", "1、先还电池，后还浮板\n\n2、请确保电池已经归还",
                "继续", "去还电池", false, new DialogWithChooseUtil.AlertDialogBtnClickListener() {
                    @Override
                    public void clickPositive(AlertDialog dialog) {
                        timerBackAlertWakeBoardTip.cancel();
                        BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 = 12;
                        BACK_TOTAL_TIME_30 = 30;
                        dialog.dismiss();
                        backWakeboardDialog(needItemCode);
                    }

                    @Override
                    public void clickNegative(AlertDialog dialog) {
                        timerBackAlertWakeBoardTip.cancel();
                        BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 = 12;
                        BACK_TOTAL_TIME_30 = 30;
                        dialog.dismiss();
                    }
                });

        if (DialogWithChooseUtil.positiveButton != null) {
            startBackAlertWakeBoardTipTimer();
        }
    }


    AlertDialog alertDialogWakeBoardTip = null;

    // 弹出浮板 -- 弹框
    private void backWakeboardDialog(String needItemCode) {

        String itemCode = getItemCode(Integer.parseInt(needItemCode));
        TaskCommand taskCommand = new TaskCommand(itemCode, "51", 1);
        taskQueue.add(taskCommand);
        openDoorTaskQueue.add(itemCode);
        if (!responseCloseDoorTaskList.containsKey(itemCode)) {
            responseCloseDoorTaskList.put(itemCode, "2");
            backCloseDoorTaskQueue.add(itemCode);
        }
        nowBackingWakeboard = itemCode;


        DialogUtil.showAlertDialog(MainActivity.this, R.mipmap.back_device, "归还浮板提示", "浮板仓门【" + needItemCode + "】已经打开，请归还浮板并关好仓门！",
                "确定", "", false, new DialogUtil.AlertDialogBtnClickListener() {
                    @Override
                    public void clickPositive(AlertDialog dialog) {
                        //Toast.makeText(MainActivity.this, "点击了确定的按钮", Toast.LENGTH_SHORT).show();
                        if (StringUtils.isEmpty(nowBackingWakeboard)) {
                            timerBackAlertWakeBoard.cancel();
                            BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;

                            Toast.makeText(MainActivity.this, "当前浮板已归还", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                           /* mBtnBackBattery.setVisibility(View.GONE);
                            mBtnBackWakeboard.setVisibility(View.VISIBLE);*/
                            mLlIndex3.setVisibility(View.GONE);
                            mLlIndex3.setAnimation(AnimationUtil.moveToViewBottom());
                            mLlIndex1.setVisibility(View.VISIBLE);
                            mLlIndex1.setAnimation(AnimationUtil.moveToViewLocation());
                        } else {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.buttonDialog);
                            alertDialogWakeBoardTip = builder.setIcon(R.mipmap.back_error)
                                    .setTitle("提示")
                                    .setMessage("请先归还浮板，如已归还，请拿出再次重放！")
                                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            TaskCommand taskCommand = new TaskCommand(nowBackingWakeboard, "51", 1);
                                            taskQueue.add(taskCommand);
                                            openDoorTaskQueue.add(nowBackingWakeboard);
                                        }
                                    })
                                    .create();

                            alertDialogWakeBoardTip.show();
                            BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;
                        }
                    }

                    @Override
                    public void clickNegative() {
                        Toast.makeText(MainActivity.this, "已取消", Toast.LENGTH_SHORT).show();
                        if(timerBackAlertWakeBoard != null){
                            timerBackAlertWakeBoard.cancel();
                            BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;
                        }
                    }
                });

        if (DialogUtil.positiveButton != null) {
            startBackAlertWakeBoardTimer();
        }
    }

    private void requestAppUpgrade() {
        //Toast.makeText(MainActivity.this,"当前版本为："+ AppInfoUtils.getVersionName(),Toast.LENGTH_LONG).show();

        HttpUtil.sendAppUpgradeInfoHttpRequest(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                UpdateInfo updateInfo = Utility.handleAppUpgradeInfoResponse(responseText);
                if (updateInfo != null && "1".equals(updateInfo.code)) {
                    if (UpdateUtils.newInstance().isNewest(updateInfo)) {
                        UpdaterConfig config = new UpdaterConfig.Builder(MainActivity.this)
                                .setFileUrl(updateInfo.data.getUrl())
                                .setCanMediaScanner(true)
                                .setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                                        | DownloadManager.Request.NETWORK_WIFI)
                                .build();
                        Updater.get().showLog(true).download(config);
                    }
                } else {
                    //Toast.makeText(MainActivity.this, updateInfo.msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(MainActivity.this, "网络连接失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }

    private void requestDeviceInfo() {
        HttpUtil.sendDeviceInfoHttpRequest(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Log.e("tianmin", "device: "+responseText);
                final DeviceInfo deviceInfo = Utility.handleDeviceInfoResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (deviceInfo != null && "1".equals(deviceInfo.code)) {
                            /*SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather", responseText);
                            editor.apply();
                            mWeatherId = weather.basic.weatherId;
                            showWeatherInfo(weather);*/
                            showDeviceInfo(deviceInfo);
                        } else {
                            Toast.makeText(MainActivity.this, deviceInfo.msg, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.e("tianmin", "faile: "+e.getLocalizedMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取设备信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }

    private void requestAdImage(int bid) {
        HttpUtil.sendAdMediaHttpRequest(bid, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                Log.d("tianmin",responseText);
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(responseText);
                    if (jsonObj == null) return;
                    String content = jsonObj.getJSONObject("data").getString("content");

                    JSONObject jsonContent = new JSONObject(content);
                    JSONArray imgPathArr = jsonContent.getJSONArray("urls");
                    List<String> imgUrlPaths = new ArrayList<>();
                    if (imgPathArr != null) {
                        for (int i = 0; i < imgPathArr.length(); i++) {
                            imgUrlPaths.add(imgPathArr.getString(i));
                        }

                        String currentTemplate = SPUtils.getInstance().getString("currentTemplate");
                        if (currentTemplate.equals("image")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ImageDownload.downLoadImages(MainActivity.this, imageFragment.banner, imgUrlPaths, 1);
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取广告图片失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void requestAdVideo(int bid) {
        HttpUtil.sendAdMediaHttpRequest(bid, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(responseText);
                    if (jsonObj == null) return;
                    String content = jsonObj.getJSONObject("data").getString("content");

                    JSONObject jsonContent = new JSONObject(content);
                    JSONArray videoPathArr = jsonContent.getJSONArray("urls");
                    List<String> videoUrlPaths = new ArrayList<>();
                    if (videoPathArr != null) {
                        for (int i = 0; i < videoPathArr.length(); i++) {
                            videoUrlPaths.add(videoPathArr.getString(i));
                        }

                        String currentTemplate = SPUtils.getInstance().getString("currentTemplate");
                        if (currentTemplate.equals("video")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    VideoDownload.downLoadVideo(MainActivity.this, videoFragment.player, videoUrlPaths);
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取设备信息失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void requestAdVideoImage(int bid) {
        HttpUtil.sendAdMediaHttpRequest(bid, new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                JSONObject jsonObj = null;
                try {
                    jsonObj = new JSONObject(responseText);
                    if (jsonObj == null) return;
                    String content = jsonObj.getJSONObject("data").getString("content");

                    JSONObject jsonContent = new JSONObject(content);
                    JSONArray imgPathArr = jsonContent.getJSONArray("urls");
                    List<String> imgUrlPaths = new ArrayList<>();
                    if (imgPathArr != null) {
                        for (int i = 0; i < imgPathArr.length(); i++) {
                            imgUrlPaths.add(imgPathArr.getString(i));
                        }

                        String currentTemplate = SPUtils.getInstance().getString("currentTemplate");
                        if (currentTemplate.equals("video")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    ImageDownload.downLoadImages(MainActivity.this, videoFragment.banner, imgUrlPaths, 2);
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "获取广告图片失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private void requestUpdateItems() {
        HttpUtil.sendUpdateItems(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e(TAG, "================更新成功==============");
                responseCloseDoorTaskList.clear();
                backCloseDoorTaskQueue.clear();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }
        });
    }

    private void requestUploadOpenLog(String logFilePath, String fileName) throws IOException {
        String filePath = logFilePath + fileName;
        HttpUtil.sendUploadOpenLogHttpRequest(filePath, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(MainActivity.TAG, "上传失败：" + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseText = response.body().string();
                Log.e(MainActivity.TAG, "上传成功：" + responseText);
            }
        });
    }


    private void showDeviceInfo(DeviceInfo deviceInfo) {

        mTvName.setText(deviceInfo.data.name);
        mTvCode.setText(deviceInfo.data.code);
        mTvFooter.setText(deviceInfo.data.anno_tip);
        mTvFees.setText(deviceInfo.data.wx_fee_tip);
        SPUtils.getInstance().put("device_title", deviceInfo.data.name);
        SPUtils.getInstance().put("device_code", deviceInfo.data.code);

        if (!StringUtils.isEmpty(deviceInfo.data.uad)) {
            SPUtils.getInstance().put("u", deviceInfo.data.uad);
            SPUtils.getInstance().put("p", deviceInfo.data.pad);
        }

        if (!StringUtils.isEmpty(deviceInfo.data.logo)) {
            Glide.with(MainActivity.this).load(deviceInfo.data.logo).into(mLogo);
        } else {
            mLogo.setImageResource(R.mipmap.logo);
        }

        if (!StringUtils.isEmpty(deviceInfo.data.qr_image)) {
            Glide.with(MainActivity.this).load(deviceInfo.data.qr_image).into(mIvWeixin);
        }
    }

    private void initSocket() {
        mInfo = new ConnectionInfo(ConstUtil.remoteIp, ConstUtil.remotePort);
        mManager = OkSocket.open(mInfo);
        final Handler handler = new Handler(Looper.getMainLooper());
        //builder.setReconnectionManager(new NoneReconnect());//关闭重连管理器
        mManager.option(new OkSocketOptions.Builder(mManager.getOption()).setReconnectionManager(OkSocketOptions.getDefault()
                .getReconnectionManager()).build());//打开重连管理器

        OkSocketOptions.Builder builder = new OkSocketOptions.Builder();
        builder.setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
            @Override
            public void handleCallbackEvent(ActionDispatcher.ActionRunnable runnable) {
                handler.post(runnable);
            }
        });

        mManager.option(builder.build());
        mManager.registerReceiver(adapter);


        if (mManager == null) {
            return;
        }
        if (!mManager.isConnect()) {
            mManager.connect();
        }
        isSocketInited = true;
    }

    private SocketActionAdapter adapter = new SocketActionAdapter() {

        // Socket连接成功回调
        @Override
        public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
            LogMyInfoSend("连接成功！");
//            mManager.send(new HandShakeBean());

            //心跳  脈搏頻率間隔毫秒數
            long frequency = 10000;
            OkSocketOptions okOptions = new OkSocketOptions.Builder(mManager.getOption()).setPulseFrequency(frequency).build();
            mManager.option(okOptions);

            mManager.getPulseManager().setPulseSendable(new PulseBean());

//            OkSocket.open(info).send(new TestSendData("1222222",0));//链式编程调用
            if (mManager != null) {
                mManager.send(new LoginBean());
                if (mSerialPortHelper == null) {
                    open();
                }

                requestDeviceInfo();
                requestAppUpgrade();

                // 显示当前网络
                if (NetworkUtils.getNetworkType() == NetworkUtils.NetworkType.NETWORK_WIFI) {
                    mIvNetState.setImageResource(R.mipmap.wifi);
                } else {
                    mIvNetState.setImageResource(R.mipmap.net_fg);
                }

                /*if(NetworkUtils.getNetworkType() == NetworkUtils.NetworkType.NETWORK_4G){
                    mIvNetState.setImageResource(R.mipmap.net_fg);
                }*/

                //mTvInfo.setText("设备【" + ConstUtil.deviceNo + "】连接成功");
            }
        }

        // Socket连接状态由连接->断开回调
        @Override
        public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
            //mTvInfo.setText("设备【" + ConstUtil.deviceNo + "】连接异常");

            if (e != null) {
                LogMyInfoSend("异常断开(Disconnected with exception):" + e.getMessage());
            } else {
                LogMyInfoSend("正常断开(Disconnect Manually)");
            }
        }

        // Socket连接失败回调
        @Override
        public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
            //mTvInfo.setText("设备【" + ConstUtil.deviceNo + "】连接失败");

            LogMyInfoSend("连接失败(Connecting Failed)");
        }

        // Socket从服务器读取到字节回调
        @Override
        public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
            String str = new String(data.getBodyBytes(), Charset.forName("utf-8"));
            LogMyInfoReceive("收到数据："+str);
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            String cmd = jsonObject.get("cmd").getAsString();
            switch (cmd) {
                // 心跳应答
                case "aa": {
                    mManager.getPulseManager().feed();
                    break;
                }

                // 开门
                case "51": {

                    String itemCode = jsonObject.get("msg").getAsString();
                    int flag = jsonObject.get("flag").getAsInt();

                    if (flag == 1) {
                        /*ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                        Charging charging = chargingDao.queryBuilder().where(ChargingDao.Properties.ItemCode.eq(getItemCodeForDec(itemCode))).unique();
                        if (charging != null) {
                            wbList.add(charging.getInfoCode());
                        } else {
                            // 从镜像里去获取数据
                            ChargingMirrorDao chargingMirrorDao = MyApplication.getDaoInstant().getChargingMirrorDao();
                            ChargingMirror chargingMirror = chargingMirrorDao.queryBuilder().where(ChargingMirrorDao.Properties.ItemCode.eq(getItemCodeForDec(itemCode))).where(ChargingMirrorDao.Properties.DoorStatus.eq("00")).unique();
                            if (chargingMirror != null) {
                                wbList.add(chargingMirror.getInfoCode());
                            }
                        }*/
                        borrowCloseDoorTaskQueue.add(itemCode);
                        // 借
                        responseCloseDoorTaskList.put(itemCode, "1");
                    }
                    if (flag == 2) {
                        backCloseDoorTaskQueue.add(itemCode);
                        // 还
                        responseCloseDoorTaskList.put(itemCode, "2");
                    }
                    if (flag == 3) {
                        // web开门
                        borrowCloseDoorTaskQueue.add(itemCode);
                        //responseCloseDoorTaskList.put(itemCode, "3");
                    }

                    TaskCommand taskCommand = new TaskCommand(itemCode, cmd, flag);
                    taskQueue.add(taskCommand);
                    openDoorTaskQueue.add(itemCode);

                    String content = "收到开门：" + str;

                    uploadLog(content);



                    break;
                }

                // 关机
                case "54": {
                    String content = "收到关机：" + str;
                    uploadLog(content);
                    ZtlManager.GetInstance().shutdown();
                    break;
                }

                // 重启
                case "55": {
                    ZtlManager.GetInstance().reboot(0);
                    break;
                }

                // 设置仓号是否可用
                case "61": {
                    String itemCode = jsonObject.get("msg").getAsString();
                    int flag = jsonObject.get("flag").getAsInt();
                    ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                    Charging charging = chargingDao.queryBuilder().where(ChargingDao.Properties.ItemCode.eq(getItemCodeForDec(itemCode))).unique();
                    if (charging != null) {
                        charging.setIsAvailable(flag);
                        chargingDao.update(charging);
                    }

                    ChargingMirrorDao chargingMirrorDao = MyApplication.getDaoInstant().getChargingMirrorDao();
                    ChargingMirror chargingMirror = chargingMirrorDao.queryBuilder().where(ChargingMirrorDao.Properties.ItemCode.eq(getItemCodeForDec(itemCode))).unique();
                    if (chargingMirror != null) {
                        chargingMirror.setIsAvailable(flag);
                        chargingMirrorDao.update(chargingMirror);
                    }

                    break;
                }

                // 广告基本信息
                case "65": {
                    requestDeviceInfo();
                    break;
                }

                // 广告图片
                case "66": {
                    int msg = jsonObject.get("msg").getAsInt();
                    requestAdImage(msg);
                    break;
                }

                // 广告视频
                case "67": {
                    int msg = jsonObject.get("msg").getAsInt();
                    requestAdVideo(msg);
                    break;
                }

                // 广告视频图片
                case "68": {
                    int msg = jsonObject.get("msg").getAsInt();
                    requestAdVideoImage(msg);
                    break;
                }

                // 广告切换
                case "69": {
                    int msg = jsonObject.get("msg").getAsInt();
                    handleSwitchTemplate(msg);
                    break;
                }

                // 获取当前版本号
                case "71": {
                    mManager.send(new NowVersionBean());
                    break;
                }

                // 升级
                case "72": {
                    requestAppUpgrade();
                    break;
                }

                // app 退出
                case "73": {
                    SPUtils.getInstance().put("stateData", "");
                    AppUtils.exitApp();
                }

                // app 重启
                case "74": {
                    SPUtils.getInstance().put("stateData", "");
                    AppUtils.relaunchApp(true);
                }

                // 上传开门日志
                case "80": {
                    String fileName = jsonObject.get("msg").getAsString() + ".txt";
                    try {
                        requestUploadOpenLog(logFilePath, fileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                // 登录成功 - 应答
                case "a0": {

                }


                default:
                    break;
            }
        }

        // Socket写给服务器字节后回调
        @Override
        public void onSocketWriteResponse(ConnectionInfo info, String action, ISendable data) {
            byte[] bytes = data.parse();
            //bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            if (!StringUtils.isEmpty(str)) {
                String cmd = str.substring(12, 14);
                switch (cmd) {
                    case "A0": {
                        // 登录成功，进行喂狗操作
                        mManager.getPulseManager().pulse();
                        break;
                    }
                    default:
                        LogMyInfoSend("发送:" + str);
                }
            }
        }

        // 发送心跳后的回调
        /*@Override
        public void onPulseSend(ConnectionInfo info, IPulseSendable data) {
            byte[] bytes = data.parse();
            //bytes = Arrays.copyOfRange(bytes, 4, bytes.length);
            String str = new String(bytes, Charset.forName("utf-8"));
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            int cmd = jsonObject.get("cmd").getAsInt();
            if (cmd == 1) {
                LogMyInfoSend("发送心跳包(Heartbeat Sending)");
            }
        }*/
    };

    private void handleSwitchTemplate(int msg) {
        String currentTemplate = SPUtils.getInstance().getString("currentTemplate");
        if (msg == 1 && !currentTemplate.equals("image")) {
            SPUtils.getInstance().put("currentTemplate", "image");
            changeFragment("image");
        }
        if (msg == 2 && !currentTemplate.equals("video")) {
            SPUtils.getInstance().put("currentTemplate", "video");
            changeFragment("video");
        }
    }

    private void changeFragment(String template) {

        if (template.equals("image")) {
            imageFragment = ImageFragment.newInstance();
            baseFragment = imageFragment;
        } else if (template.equals("video")) {
            videoFragment = VideoFragment.newInstance();
            baseFragment = videoFragment;
        }

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, baseFragment);
        fragmentTransaction.commit();
    }

    public void showFragment(Fragment fragment) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout, fragment);
        fragmentTransaction.commit();
    }

    private void LogMyInfoSend(String msg) {
        Log.d("tianmin",msg);
    }

    private void LogMyInfoReceive(String msg) {
        Log.d("tianmin","长连接数据:" + msg);
    }

    private void open() {
        if (mSerialPortHelper == null) {
            String serialNo = DeviceUtil.getSerialNumber();
            mSerialPortHelper = new SerialPortHelper();
            mSerialPortHelper.setPort("/dev/ttyS4"); // 定昌电子

            /*if (serialNo.equals("000051") || serialNo.equals("000052")) {
                mSerialPortHelper.setPort("/dev/ttyS1");
            } else {
                mSerialPortHelper.setPort("/dev/ttyS4"); //
            }*/
            //
            mSerialPortHelper.setBaudRate(9600); // 115200
            mSerialPortHelper.setStopBits(STOPB.getStopBit(STOPB.B1));
            mSerialPortHelper.setDataBits(DATAB.getDataBit(DATAB.CS8));
            mSerialPortHelper.setParity(PARITY.getParity(PARITY.NONE));
            mSerialPortHelper.setFlowCon(FLOWCON.getFlowCon(FLOWCON.NONE));
        }
        Log.i(TAG, "open: " + Arrays.toString(mSerialPortHelper.getAllDeicesPath()));
        mSerialPortHelper.setIOpenSerialPortListener(new IOpenSerialPortListener() {
            @Override
            public void onSuccess(final File device) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(MainActivity.this, device.getPath() + " :串口打开成功", Toast.LENGTH_SHORT).show();
                        Toast.makeText(MainActivity.this, "init finished", Toast.LENGTH_SHORT).show();
                        mSendThread.setResume();
                        executeHeartBeatEveryMinute();
                    }
                });
            }

            @Override
            public void onFail(File device, Status status) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (status) {
                            case NO_READ_WRITE_PERMISSION:
                                Toast.makeText(MainActivity.this, device.getPath() + " :没有读写权限", Toast.LENGTH_SHORT).show();
                                break;
                            case OPEN_FAIL:
                            default:
                                Toast.makeText(MainActivity.this, device.getPath() + " :串口打开失败", Toast.LENGTH_SHORT).show();
                                break;
                        }
                    }
                });
            }

        });
        mSerialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
            @Override
            public void onDataReceived(byte[] bytes) {
                // Log.i(TAG, "onDataReceived: " + Arrays.toString(bytes));

                dataQueue.add(bytes);

                //Log.i(TAG, "onDataReceived: " + ByteUtils.byteArrToHex(bytes));


            }

            @Override
            public void onDataSend(byte[] bytes) {
                Log.e(TAG, "【" + TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "】- onDataSend: " + ByteUtils.byteArrToHex(bytes));
            }
        });

        MyApplication applicationContext = (MyApplication) getApplicationContext();
        applicationContext.setSerialPortHelper(mSerialPortHelper);

        mProgressDataThread = new ProgressDataThread();
        mProgressDataThread.start();

        mSendThread = new SendThread();
        mSendThread.start();

        Log.i(TAG, "open: " + mSerialPortHelper.open());
    }

    public void relese() {
        if (mProgressDataThread != null) mProgressDataThread.interrupt();
        if (mSendThread != null) mSendThread.interrupt();
    }

    private class ProgressDataThread extends Thread {
        public void run() {
            while (!isInterrupted()) {
                byte[] take;
                try {
                    take = dataQueue.take();
                    if (take != null && take.length > 0) {
                        //Log.i(TAG, "数组阻塞队列......");
                        //Log.i(TAG, take.toString());
                        progressData(take);
                    }
                } catch (InterruptedException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private ByteArrayOutputStream baos = new ByteArrayOutputStream();

    private void progressData(byte[] bytes) throws IOException {
        baos.write(bytes);
        //其他数据帧 帧尾0xFF 0xFC 0xFD 0xFF
        byte[] buffer = baos.toByteArray();
        if (buffer[0] != (byte) 0x61) {
            baos.reset();
        }
        boolean isFrameEnd = buffer[0] == (byte) 0x61 && buffer[buffer.length - 1] == (byte) 0xDF && buffer[buffer.length - 2] == (byte) 0xDF;


        if (isFrameEnd) {
            final byte[] data = baos.toByteArray();

            String responseHex = ByteUtils.byteArrToHex(data).toLowerCase();
            Log.i(TAG, "【" + TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "】- onDataReceived: " + responseHex);

            String infoIdentity = UploadDataUtil.getInfoIdentity(responseHex);
            String itemCode = UploadDataUtil.getItemCodeHex(responseHex);
            String infoCode = UploadDataUtil.getInfoCode(responseHex);
            String doorStatus = UploadDataUtil.getDoorStatus(responseHex);

            /*if (!StringUtils.isEmpty(nowCmdItemCode) && itemCode.equals(nowCmdItemCode)) {
                nowCmdItemCode = "";
            }*/

            /*if(!StringUtils.isEmpty(nowCmdItemCode) && !itemCode.equals(nowCmdItemCode))
            {
                Log.e(TAG, "【开门失败】，开门失败，重新添加任务 - " + itemCode);
                TaskCommand taskCommand = new TaskCommand(nowCmdItemCode, "51", 1);
                taskQueue.add(taskCommand);
                nowCmdItemCode = "";
            }else{
                nowCmdItemCode = "";
            }*/

            if (openDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A1") && doorStatus.equals("01")) {
                Log.e(TAG, "开门立即数据回复：" + responseHex);
                String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "  【借还-开门回复】- [" + infoCode + " -" + getItemCodeForDec(itemCode) + "] " + responseHex;
                FileUtils.writeTxtToFile(log, logFilePath, logFileName);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mManager.isConnect()) {
                            mManager.send(new UploadBean(ByteUtils.byteArrToHex(data)));
                        }
                    }
                });
                openDoorTaskQueue.remove(itemCode);
            }

            if (taskQueue != null && taskQueue.size() == 0 && openDoorTaskQueue != null && openDoorTaskQueue.size() > 0) {
                for (String item : openDoorTaskQueue) {
                    TaskCommand taskCommand = new TaskCommand(item, "51", 1);
                    taskQueue.add(taskCommand);
                }
            }

            // borrowCloseDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A3") && doorStatus.equals("00") && infoCode.equals("00000000")
            if (borrowCloseDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A3") && doorStatus.equals("00")) {

                // 处理借的时候，电池拿走，再关门，2秒之内完成操作，还读到卡的情况
                ChargingDelayDao chargingDelayDao = MyApplication.getDaoInstant().getChargingDelayDao();
                ChargingDelay chargingDelay = chargingDelayDao.queryBuilder().where(ChargingDelayDao.Properties.ItemCode.eq(UploadDataUtil.getItemCode(responseHex))).unique();
                if (chargingDelay != null && chargingDelay.getItemFlag() == 1) {
                    long itemCodeMillis = TimeUtils.date2Millis(chargingDelay.getUpdateTime());
                    long nowMillis = TimeUtils.date2Millis(new Date());
                    if (nowMillis - itemCodeMillis > 5000) {
                        Log.e(TAG, "itemCodeMillis：" + itemCodeMillis + " nowMillis:" + nowMillis + " responseHex:" + responseHex);
                        handleBorrowClosedData(responseHex, itemCode, infoCode,1);

                        chargingDelay.setInfoCode(infoCode);
                        chargingDelay.setUpdateTime(new Date());
                        chargingDelay.setItemFlag(0);
                        chargingDelayDao.update(chargingDelay);

                        // 记录一次最新的备用
                        ChargingMirrorDao chargingMirrorDao = MyApplication.getDaoInstant().getChargingMirrorDao();
                        ChargingMirror chargingMirror = chargingMirrorDao.queryBuilder().where(ChargingMirrorDao.Properties.ItemCode.eq(UploadDataUtil.getItemCode(responseHex))).unique();
                        if (chargingMirror != null) {
                            chargingMirror.setDoorStatus("00");
                            chargingMirror.setInfoCode(infoCode);
                            chargingMirrorDao.update(chargingMirror);
                        }
                    }
                } else {
                    if (chargingDelay != null && !infoCode.equals("00000000")) {
                        chargingDelay.setInfoCode(infoCode);
                        chargingDelay.setUpdateTime(new Date());
                        chargingDelay.setItemFlag(1);
                        chargingDelayDao.update(chargingDelay);
                    } else {
                        // 空仓门，直接返回
                        handleBorrowClosedData(responseHex, itemCode, infoCode,2);

                    }
                }
            }

            if (backCloseDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A3") && doorStatus.equals("00") && !infoCode.equals("00000000")) {
                Log.e(TAG, "【还-关门】开门之后，关门数据回复：" + responseHex);
                String dataPackage = UploadDataUtil.getCloseDoorDataPackage(responseHex);
                String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "  【还回-关门回复】- [" + infoCode + " -" + getItemCodeForDec(itemCode) + "] " + dataPackage;
                FileUtils.writeTxtToFile(log, logFilePath, logFileName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mManager.isConnect()) {
                            mManager.send(new UploadBean(dataPackage));
                        }
                    }
                });
                backCloseDoorTaskQueue.remove(itemCode);
                responseCloseDoorTaskList.keySet().removeIf(key -> key.equals(itemCode));
                if (nowBackingBattery.equals(itemCode)) {
                    nowBackingBattery = "";
                }
                if (nowBackingWakeboard.equals(itemCode)) {
                    nowBackingWakeboard = "";
                }

                // 还关门，去掉wbList中的电池编号
                /*if (wbList.contains(infoCode)) {
                    wbList.remove(infoCode);
                }*/
            }

            if (backCloseDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A3") && doorStatus.equals("00") && infoCode.equals("00000000")) {
                Log.e(TAG, "【还-关门】开门之后，关门数据回复 --- 【误关门处理】：" + responseHex);
                String dataPackage = UploadDataUtil.getCloseDoorDataPackage(responseHex);
                /*String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "  【还回-关门回复-误关门数据回复】- [" + infoCode + " -" + getItemCodeForDec(itemCode) + "] " + dataPackage;
                FileUtils.writeTxtToFile(log, logFilePath, logFileName);*/
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mManager.isConnect()) {
                            mManager.send(new UploadBean(dataPackage));
                        }
                    }
                });
            }

            // 防止还电池时，门被打开，没还电池，直接关门
            // 换电池时，也会偶尔存在读不到卡的情况，所以读不到电池不能作为判断依据
            /*if (backCloseDoorTaskQueue.contains(itemCode) && infoIdentity.equals("A3") && doorStatus.equals("00") && infoCode.equals("00000000")) {

            }*/

            // DispRecData(data);
            localDataStorage(ByteUtils.byteArrToHex(data).toLowerCase());
            baos.reset();
            isFinished = true;
        }

        if (buffer.length > 19) {
            baos.reset();
        }
    }

    private void handleBorrowClosedData(String responseHex, String itemCode, String infoCode,int itemFlag) {
        Log.e(TAG, "【借-关门】开门之后，关门数据回复：" + responseHex);
        String dataPackage = UploadDataUtil.getCloseDoorDataPackage(responseHex);
        String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "  【借取-关门回复】- [" + infoCode + " -" + getItemCodeForDec(itemCode) + "] " + dataPackage;
        FileUtils.writeTxtToFile(log, logFilePath, logFileName);

        borrowCloseDoorTaskQueue.remove(itemCode);
        responseCloseDoorTaskList.keySet().removeIf(key -> key.equals(itemCode));

        // 处理借之后，直接关门的情况
        /*if (!infoCode.equals("00000000")) {
            if (wbList.contains(infoCode)) {
                wbList.remove(infoCode);
            }
        }*/

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mManager.isConnect()) {
                    mManager.send(new UploadBean(dataPackage));

                    // 借关门，有电池时，跳到 “还浮板”界面
                    /*if (!infoCode.equals("00000000") && itemFlag == 1) {
                        mBtnBackBattery.setVisibility(View.GONE);
                        mBtnBackWakeboard.setVisibility(View.VISIBLE);
                    }*/
                }
            }
        });
    }

    private void localDataStorage(String data) {
        if (!checkPackageData(data)) return;
        ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
        Charging charging = chargingDao.queryBuilder().where(ChargingDao.Properties.ItemCode.eq(UploadDataUtil.getItemCode(data))).unique();
        if (charging != null) {
            charging.setItemCode(UploadDataUtil.getItemCode(data));
            charging.setInfoCode(UploadDataUtil.getInfoCode(data));
            charging.setDianYa(UploadDataUtil.getVoltage(data));
            charging.setDianLiang(UploadDataUtil.getElectricity(data));
            charging.setDianLiu(UploadDataUtil.getCurrent(data));
            charging.setTemperature(UploadDataUtil.getTemperature(data));
            charging.setSmoke(UploadDataUtil.getSmoke(data));
            charging.setCharging(UploadDataUtil.getCharging(data));
            charging.setLighting(UploadDataUtil.getLighting(data));
            charging.setDoorStatus(UploadDataUtil.getDoorStatus(data));
            charging.setDataInfo(data);
            charging.setUpdateTime(new Date());
            chargingDao.update(charging);
        }

        ChargingMirrorDao chargingMirrorDao = MyApplication.getDaoInstant().getChargingMirrorDao();
        ChargingMirror chargingMirror = chargingMirrorDao.queryBuilder().where(ChargingMirrorDao.Properties.ItemCode.eq(UploadDataUtil.getItemCode(data))).unique();
        if (chargingMirror != null) {
            if (UploadDataUtil.getDoorStatus(data).equals("01")) {
                chargingMirror.setDoorStatus("01");
                chargingMirror.setInfoCode("00000000");
            }
            if (UploadDataUtil.getDoorStatus(data).equals("00")) {
                // 本身门是关着的
                if (chargingMirror.getDoorStatus().equals("00")) {
                    if (chargingMirror.getInfoCode().equals("00000000")) {
                        chargingMirror.setInfoCode(UploadDataUtil.getInfoCode(data));
                    }
                } else {
                    chargingMirror.setDoorStatus("00");
                    chargingMirror.setInfoCode(UploadDataUtil.getInfoCode(data));
                }
            }
            chargingMirrorDao.update(chargingMirror);
        }
    }

    private boolean checkPackageData(String data) {
        boolean result = data.length() == 40 && UploadDataUtil.getPackageHeader(data).equals("61") && UploadDataUtil.getPackageTail(data).equals("dfdf");
        return result;
    }

    private void sendDownData(String cmdText) {
        if (mSerialPortHelper != null && mSerialPortHelper.isOpen()) {
            Log.i(TAG, cmdText);
            mSerialPortHelper.sendHex(cmdText);
        }
    }

    private void close() {
        if (mSerialPortHelper != null) {
            mSerialPortHelper.close();
            Toast.makeText(MainActivity.this, " :串口已关闭", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     *
     */
    public void executeHeartBeatEveryMinute() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        Log.e(TAG, "schedule just start! time =" + TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
        executor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
                List<Charging> chargingList = chargingDao.queryBuilder().list();
                for (Charging charging : chargingList) {
                    String dataInfo = charging.getDataInfo();
                    Log.e(TAG, "当前时间：" + TimeUtils.date2String(charging.getUpdateTime(), "yyyyMMddHHmmss"));
                    long itemCodeMillis = TimeUtils.date2Millis(charging.getUpdateTime());
                    long nowMillis = TimeUtils.date2Millis(new Date());

                    if (mManager.isConnect()) {
                        if (nowMillis - itemCodeMillis < 90000) {
                            if (!StringUtils.isEmpty(dataInfo) && dataInfo.length() == 40) {
                                mManager.send(new UploadBean(UploadDataUtil.getNowStateDataPackage(dataInfo)));
                            }
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                Log.e(TAG, "runnable just do it! time =" + TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss"));
            }
        }, 3, 60, TimeUnit.SECONDS);
    }


    public static BlockingQueue<String> closeDoorTaskQueue = new LinkedBlockingQueue<>();

    private class SendThread extends Thread {
        public boolean suspendFlag = true;// 控制线程的执行
        public int boxCount = 25;
        public int current = 1;
        long startTime = 0L;

        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {

                synchronized (this) {
                    while (suspendFlag) {
                        try {
                            wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                // 添加后台命令
                BlockingQueue<String> backOpenDoorTaskQueue = MyApplication.getBackOpenDoorTaskQueue();
                if (backOpenDoorTaskQueue != null && backOpenDoorTaskQueue.size() > 0) {
                    String itemCode = null;
                    try {
                        itemCode = MyApplication.getBackOpenDoorTaskQueue().take();
                        Log.e("=====取出仓号=====", itemCode);
                        if (!StringUtils.isEmpty(itemCode)) {
                            addBackOpenCommand(itemCode);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                if (isFinished) {
                    //Log.e(TAG,"执行成功，进行下一条指令");
                    isFinished = false;

                    // 开门任务处理
                    if (taskQueue != null && taskQueue.size() > 0) {
                        try {
                            TaskCommand taskCommand = taskQueue.take();
                            Log.e(TAG, "执行任务开始111111111111111111111   任务：" + taskCommand.getItemCode());
                            if (taskCommand.getCmd().equals("51")) {
                                nowCmdItemCode = taskCommand.getItemCode();
                                String hexCmdStr = DownCommand.getOpenDoorCmdHex(taskCommand.getItemCode());
                                sendDownData(hexCmdStr);

                                String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "   " + hexCmdStr+"-"+getItemCodeForDec(taskCommand.getItemCode());
                                FileUtils.writeTxtToFile("", logFilePath, logFileName);
                                FileUtils.writeTxtToFile(log, logFilePath, logFileName);
                                startTime = System.currentTimeMillis();
                                //Thread.sleep(500L);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else if (closeDoorTaskQueue != null && closeDoorTaskQueue.size() > 0) {
                        try {
                            String itemCode = closeDoorTaskQueue.take();
                            if (!StringUtils.isEmpty(itemCode)) {
                                sendHeartBeatCmd(itemCode);
                                startTime = System.currentTimeMillis();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    } else {
                        //Log.e(TAG,"无任务执行11111.。。。。。。。。。。。。。");
                        if (current <= 25) {
                            sendHeartBeatCmd();
                            current++;
                        } else {
                            current = 1;
                        }
                        startTime = System.currentTimeMillis();

                        if (responseCloseDoorTaskList != null && responseCloseDoorTaskList.size() > 0) {
                            for (String item : responseCloseDoorTaskList.keySet()) {
                                closeDoorTaskQueue.add(item);
                            }
                        }
                    }
                } else {

                    long endTime = System.currentTimeMillis();
                    long lenTime = endTime - startTime;

                    if (lenTime > 500L) {

                        //Log.e(TAG,"超过500ms，当前："+lenTime+"，进入执行。。。。。。。。。。。。");

                        // 开门任务处理
                        if (taskQueue != null && taskQueue.size() > 0) {
                            try {
                                TaskCommand taskCommand = taskQueue.take();
                                Log.e(TAG, "执行任务开始22222222222222222222   任务：" + taskCommand.getItemCode());
                                if (taskCommand.getCmd().equals("51")) {
                                    /*if(!StringUtils.isEmpty(nowCmdItemCode)) {
                                        // 先添加未执行任务
                                        Log.e(TAG, "未执行任务   任务仓号：" + nowCmdItemCode);
                                        taskList.add(nowCmdItemCode);
                                        Log.e(TAG,"任务列表："+taskList);
                                        TaskCommand noExecuteTaskCommand = new TaskCommand(nowCmdItemCode, "51", 1);
                                        taskQueue.add(noExecuteTaskCommand);
                                    }*/

                                    nowCmdItemCode = taskCommand.getItemCode();
                                    String hexCmdStr = DownCommand.getOpenDoorCmdHex(taskCommand.getItemCode());
                                    sendDownData(hexCmdStr);

                                    String log = TimeUtils.date2String(new Date(), "yyyy-MM-dd HH:mm:ss.SSS") + "   " + hexCmdStr+"-"+getItemCodeForDec(taskCommand.getItemCode());
                                    FileUtils.writeTxtToFile("", logFilePath, logFileName);
                                    FileUtils.writeTxtToFile(log, logFilePath, logFileName);

                                    startTime = System.currentTimeMillis();

                                    //Thread.sleep(500L);
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else if (closeDoorTaskQueue != null && closeDoorTaskQueue.size() > 0) {
                            try {
                                String itemCode = closeDoorTaskQueue.take();
                                if (!StringUtils.isEmpty(itemCode)) {
                                    sendHeartBeatCmd(itemCode);
                                    startTime = System.currentTimeMillis();
                                }
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        } else {
                            //Log.e(TAG,"无任务执行22222.。。。。。。。。。。。。。");
                            if (current <= 25) {
                                sendHeartBeatCmd();
                                current++;
                            } else {
                                current = 1;
                            }
                            startTime = System.currentTimeMillis();

                            if (responseCloseDoorTaskList != null && responseCloseDoorTaskList.size() > 0) {
                                for (String item : responseCloseDoorTaskList.keySet()) {
                                    closeDoorTaskQueue.add(item);
                                }
                            }
                        }
                    }
                }
            }
        }

        private String getItemCode() {
            String itemCode = "";

            if (current <= 9) {
                itemCode = "0" + current;
            }

            if (9 < current && current <= 15) {
                itemCode = "0" + Integer.toHexString(current);
            }

            if (current > 15) {
                itemCode = Integer.toHexString(current);
            }

            return itemCode;
        }

        public void sendHeartBeatCmd() {
            if (mSerialPortHelper != null) {
                String strCmd = "16" + getItemCode() + "B100DFDF";
                mSerialPortHelper.sendHex(strCmd);
                //Log.i(TAG,strCmd);
                //logSend("----->" + strCmd,1);
            }
        }

        public void sendHeartBeatCmd(String itemCode) {
            if (mSerialPortHelper != null) {
                String strCmd = "16" + itemCode + "B100DFDF";
                mSerialPortHelper.sendHex(strCmd);
            }
        }

        //线程暂停
        public void setSuspendFlag() {
            this.suspendFlag = true;
        }

        //唤醒线程
        public synchronized void setResume() {
            this.suspendFlag = false;
            notify();
        }
    }

    private String getItemCode(int itemNum) {
        String itemCode = "";

        if (itemNum <= 9) {
            itemCode = "0" + itemNum;
        }

        if (9 < itemNum && itemNum <= 15) {
            itemCode = "0" + Integer.toHexString(itemNum);
        }

        if (itemNum > 15) {
            itemCode = Integer.toHexString(itemNum);
        }

        return itemCode;
    }

    public static String getItemCodeForDec(String itemCode) {
        int i = Integer.parseInt(itemCode, 16);
        if (i < 10) {
            return "0" + i;
        } else {
            return String.valueOf(i);
        }
    }

    // 开始借计时【倒计时】
    private void startBorrowTimer() {
        timerBorrow = new Timer();
        /**
         * 每一秒发送一次消息给handler更新UI
         * schedule(TimerTask task, long delay, long period)
         */
        timerBorrow.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBtnReturn.setText("返回(" + BORROW_TOTAL_TIME_20 + ")");
                        if (BORROW_TOTAL_TIME_20 == 0) {
                            timerBorrow.cancel(); //0秒结束
                            BORROW_TOTAL_TIME_20 = 20;
                            showBorrowBackUI();
                        }
                        BORROW_TOTAL_TIME_20--;
                    }
                });
            }
        }, 0, 1000);
    }

    // 开始还计时【倒计时】
    private void startBackTimer() {
        timerBack = new Timer();
        /**
         * 每一秒发送一次消息给handler更新UI
         * schedule(TimerTask task, long delay, long period)
         */
        timerBack.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBtnReturnBack.setText("返回(" + BACK_TOTAL_TIME_30 + ")");
                        if (BACK_TOTAL_TIME_30 == 0) {
                            timerBack.cancel(); //0秒结束
                            BACK_TOTAL_TIME_30 = 30;
                            showBackBorrowUI();
                        }
                        BACK_TOTAL_TIME_30--;
                    }
                });
            }
        }, 0, 1000);
    }

    // 用于还电池【门窗弹开】 计时
    private void startBackAlertBatteryTimer() {
        timerBackAlertBattery = new Timer();
        /**
         * 每一秒发送一次消息给handler更新UI
         * schedule(TimerTask task, long delay, long period)
         */
        timerBackAlertBattery.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtil.positiveButton.setText("确认(" + BACK_ALERT_BATTERY_TOTAL_TIME_30 + ")");
                        if (BACK_ALERT_BATTERY_TOTAL_TIME_30 == 0) {
                            timerBackAlertBattery.cancel(); //0秒结束
                            BACK_ALERT_BATTERY_TOTAL_TIME_30 = 30;
                            if (alertDialogBatteryTip != null) {
                                alertDialogBatteryTip.dismiss();
                            }
                            if (DialogUtil.dialog != null) {
                                DialogUtil.dialog.dismiss();
                                showBackBorrowUI();
                            }
                        }
                        BACK_ALERT_BATTERY_TOTAL_TIME_30--;
                    }
                });
            }
        }, 0, 1000);
    }

    // 用于还电池【门窗弹开】 计时
    private void startBackAlertWakeBoardTipTimer() {
        timerBackAlertWakeBoardTip = new Timer();
        timerBackAlertWakeBoardTip.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogWithChooseUtil.positiveButton.setText("继续(" + BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 + ")");
                        if (BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 == 0) {
                            timerBackAlertWakeBoardTip.cancel(); //0秒结束
                            BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12 = 12;
                            if (DialogWithChooseUtil.dialog != null) {
                                DialogWithChooseUtil.dialog.dismiss();
                            }
                        }
                        BACK_ALERT_WAKEBOARD_TIP_TOTAL_TIME_12--;
                    }
                });
            }
        }, 0, 1000);
    }


    // 用于还电池【门窗弹开】 计时
    private void startBackAlertWakeBoardTimer() {
        timerBackAlertWakeBoard = new Timer();
        /**
         * 每一秒发送一次消息给handler更新UI
         * schedule(TimerTask task, long delay, long period)
         */
        timerBackAlertWakeBoard.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DialogUtil.positiveButton.setText("确认(" + BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 + ")");
                        if (BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 == 0) {
                            timerBackAlertWakeBoard.cancel(); //0秒结束
                            BACK_ALERT_WAKEBOARD_TOTAL_TIME_30 = 30;
                            if (alertDialogWakeBoardTip != null) {
                                alertDialogWakeBoardTip.dismiss();
                            }
                            if (DialogUtil.dialog != null) {
                                DialogUtil.dialog.dismiss();
                                showBackBorrowUI();
                            }

                            /*if (StringUtils.isEmpty(nowBackingWakeboard)) {
                                Toast.makeText(MainActivity.this, "当前浮板已归还", Toast.LENGTH_SHORT).show();
                            }*/
                        }
                        BACK_ALERT_WAKEBOARD_TOTAL_TIME_30--;
                    }
                });
            }
        }, 0, 1000);
    }

    // 借界面 - 返回，倒计时显示UI
    private void showBorrowBackUI() {
        mLlIndex2.setVisibility(View.GONE);
        mLlIndex2.setAnimation(AnimationUtil.moveToViewBottom());
        mLlIndex1.setVisibility(View.VISIBLE);
        mLlIndex1.setAnimation(AnimationUtil.moveToViewLocation());
    }

    // 还界面 - 返回，倒计时显示UI
    private void showBackBorrowUI() {
        mLlIndex3.setVisibility(View.GONE);
        mLlIndex3.setAnimation(AnimationUtil.moveToViewBottom());
        mLlIndex1.setVisibility(View.VISIBLE);
        mLlIndex1.setAnimation(AnimationUtil.moveToViewLocation());
    }


    // 连续点击五次以上显示【还浮板】按钮
    /*private void showBackWakeBoardButton() {
        if (clickCount == 0) {
            lastTimeClick = System.currentTimeMillis();
            clickCount = 1;
        } else {
            newTimeClick = System.currentTimeMillis();
            if ((newTimeClick - lastTimeClick) < timeLong) { //连续点击间隔
                clickCount += 1;
            } else {
                clickCount = 1;
            }
            lastTimeClick = newTimeClick;
            if (clickCount == 5) {  //点击次数
                clickCount = 0;
                if (mBtnBackBattery.getVisibility() == View.VISIBLE) {
                    mBtnBackBattery.setVisibility(View.GONE);
                    mBtnBackWakeboard.setVisibility(View.VISIBLE);
                    BACK_TOTAL_TIME_20 = 20;
                    timerBack.cancel();
                    mBtnReturnBack.setVisibility(View.GONE);
                } else {
                    mBtnBackBattery.setVisibility(View.VISIBLE);
                    mBtnBackWakeboard.setVisibility(View.GONE);
                    BACK_TOTAL_TIME_20 = 20;
                    //startBorrowTimer();
                    mBtnReturnBack.setVisibility(View.VISIBLE);
                    mBtnReturnBack.setText("返回");

                }
            }
        }
    }*/

    public static void releaseActivity() {
        if (responseCloseDoorTaskList != null && responseCloseDoorTaskList.size() > 0) {
            Gson gson = new GsonBuilder().create();
            SPUtils.getInstance().put("responseCloseDoorTaskList", GsonUtils.toJson(gson, responseCloseDoorTaskList));
        }
        /*if (wbList != null && wbList.size() > 0) {
            SPUtils.getInstance().put("wbList", wbList.stream().collect(Collectors.joining(",")));
        }*/
    }

    // 添加后台开门命令
    public static void addBackOpenCommand(String itemCode) {
        Log.e("=====发送指令=====", itemCode);
        //borrowCloseDoorTaskQueue.add(itemCode);
        //responseCloseDoorTaskList.put(itemCode, "3");

        TaskCommand taskCommand = new TaskCommand(itemCode, "51", 3);
        taskQueue.add(taskCommand);
        openDoorTaskQueue.add(itemCode);
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            ChargingDao chargingDao = MyApplication.getDaoInstant().getChargingDao();
            List<Charging> chargingList = chargingDao.queryBuilder().where(ChargingDao.Properties.DoorStatus.eq("01")).list();
            if (chargingList != null && chargingList.size() > 0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.buttonDialog);
                builder.setIcon(R.mipmap.back_error)
                        .setTitle("提示")
                        .setMessage("请先关好仓门，再退出App")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .create().show();
            } else {
                SPUtils.getInstance().put("stateData", "");
                AppUtils.exitApp();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void handleOpenLog() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, -15);
        Date m = c.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String before15Day = format.format(m);

        List<String> logList = FileUtils.getAllDataFileName(logFilePath);
        if (logList.size() > 0) {
            for (String logName : logList) {
                String logFileName = logName.substring(0, logName.lastIndexOf("."));
                if (before15Day.compareTo(logFileName) > 0) {
                    String filePath = logFilePath + logName;
                    com.blankj.utilcode.util.FileUtils.delete(filePath);
                }
            }
        }
    }

    public void uploadLog(String log){
        HttpUtil.sendUploadLog(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.d("tianmin","上传日志结果失败=" + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d("tianmin","上传日志成功=" + response.body().string());
            }
        },log);
    }

}